from flask import Blueprint, request
from libs.readcsv import fetchRow, forecast
import json
from flask_cors import CORS
import pandas as pd
from datetime import datetime
# from libs.forcastdata import predictmodel


forecast_bp = Blueprint("forecastapi", __name__)
cors = CORS(forecast_bp)


@forecast_bp.route('/fetchRow', methods=['GET'])
def getfetchRow():
    json_list = []
    bucketName = request.args.get('bucktName')
    data = fetchRow(bucketName)

    for index, row in data.iterrows():
        json_obj = {
            "Date": row['date'],
            "scales": float(row['count'])/100
        }
        json_list.append(json_obj)

    return json.dumps(json_list)


@forecast_bp.route('/forecast', methods=['GET'])
def getforcastdata():
    json_list = []
    bucketName = request.args.get('bucktName')
    data = forecast(bucketName)

    for index, row in data.iterrows():
        json_obj = {
            "Date": row['date'],
            "scales": row['count']
        }
        json_list.append(json_obj)

    return json.dumps(json_list)

# @forecast_bp.route('/fetchRow', methods=['GET'])
# def get_erroratedata():
#     json_list = []
#     data = erroratedata()
#     global start_time, end_time
#     start_time = request.args.get('start_time', '')  # 添加默认值 ''
#     end_time = request.args.get('end_time', '')  # 添加默认值 ''
#     start_time = start_time.strip('"')
#     end_time = end_time.strip('"')
#
#     if not bool(request.args):
#         data = data
#         # result = data.to_dict(orient='records')
#     else:
#         # 检查变量是否已有值
#         if start_time and end_time:
#             format = "%Y-%m-%d %H:%M:%S"
#             start_datetime = datetime.strptime(start_time, format)
#             end_datetime = datetime.strptime(end_time, format)
#             data = data[(data['date'] >= start_datetime) & (data['date'] <= end_datetime)]
#
#     for index, row in data.iterrows():
#         json_obj = {
#             "Date": row['date'].strftime('%Y-%m-%d %H:%M:%S'),
#             "scales": row['count']
#         }
#         json_list.append(json_obj)
#
#     return json.dumps(json_list)
#
#
# @forecast_bp.route('/forecast', methods=['GET'])
# def getforcastdata():
#     # time = request.args.get('start_time')  # 添加默认值 ''
#     # result = predictmodel(r'D:\hm\hm_project\data\output1.csv', int(time))
#     json_list = []
#     data = forcastdata()
#
#     for index, row in data.iterrows():
#         json_obj = {
#             "Date": row['date'],
#             "scales": row['count']
#         }
#         json_list.append(json_obj)
#
#     return json.dumps(json_list)
